import axios from 'axios'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/token'
import { blobValidate } from '@/utils/common'

const baseURL = import.meta.env.VITE_APP_API_BASEURL

export default {
  download(url:string) {
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data])
        saveAs(blob, decodeURIComponent(res.headers['download-filename']))
      } else {
        this.printErrMsg(res.data);
      }
    })
  },
  zip(url:any, name:any) {
    axios({
      method: 'get',
      url: baseURL + url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data], { type: 'application/zip' })
        saveAs(blob, name)
      } else {
        this.printErrMsg(res.data);
      }
    })
  },
  saveAs(text:any, name:any, opts:any) {
    saveAs(text, name, opts);
  },
  async printErrMsg(data:any) {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    ElMessage.error(rspObj.msg);
  }
}

